package com.tianshi.order.service.impl;


import com.tianshi.entity.*;

import com.tianshi.order.feign.client.ProductFeignClient;
import com.tianshi.order.mapper.CartItemMapper;
import com.tianshi.order.mapper.CartMapper;
import com.tianshi.order.mapper.OrderItemMapper;
import com.tianshi.order.mapper.OrderMapper;
import com.tianshi.order.service.OrderService;
import com.tianshi.vo.ProductVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private CartItemMapper cartItemMapper;
    @Autowired
    ProductFeignClient productFeignClient;
    @Autowired
    private OrderItemMapper orderItemMapper;
    //查询所有订单
    @Override
    public List<Orders> checkOrders() {
        return orderMapper.checkAllOrders();
    }


    @Override
    @Transactional
    public int addOrder(Long cartId) {
        if (cartId == null) {
            log.error("productId or quantity is null");
            return 0;
        }
        //获取购物车信息
        Carts carts = cartMapper.getCartByCartId(cartId);
        System.out.println(carts);
        List<CartItems> cartItemList = cartItemMapper.getCartItemByCartId(cartId);

        //插入订单
        Orders orders = new Orders();
        orders.setUserId(carts.getUserId());
        orders.setAddressId(999L);
        //订单Sn用雪花算法生成
        orders.setOrderSn(SnowFlake.getInstance().nextId());
        orders.setCreatedAt(carts.getCreatedAt());
        orders.setOrderStatus((short) 2);
        orders.setFreightAmount(0.0);
        int insert = orderMapper.insert(orders);
        Double totalAmount = 0.0;
        Double payAmount = 0.0;
        //当前购物车id 存在
        if (insert > 0) {
            //远程调用商品服务，获取商品信息
            for(CartItems cartItem:cartItemList){
                ProductVO productVO = productFeignClient.getProductByProductId(cartItem.getProductId()).getBody();
                if(productVO==null) continue;
                Products products=productVO.getProduct();
                //获取商品

                if (products != null) {
                    OrderItems orderItems = new OrderItems();
                    //订单项注入值
                    orderItems.setOrderId(orders.getOrderId());
                    orderItems.setProductId(products.getProductId());
                    orderItems.setProductName(products.getProductName());
                    orderItems.setProductImage(products.getImage());
                    orderItems.setProductPrice(products.getPrice());
                    orderItems.setQuantity(cartItem.getQuantity());
                    //订单项总价
                    orderItems.setTotalPrice(orderItems.getProductPrice() * orderItems.getQuantity());
                    orderItemMapper.insert(orderItems); //插入订单项

                    totalAmount +=orderItems.getTotalPrice() ;
                    payAmount += orderItems.getTotalPrice() ;

                    //删除购物车项
                    cartItemMapper.delete(cartItem.getItemId());
                }
            }

            cartMapper.delete(cartId);
        }
        orderMapper.updateByOrderId(orders.getOrderId(),totalAmount,payAmount);
        return insert;
    }

    @Override
    public List<Orders> checkOrderByUserId(Long userId) {
        return orderMapper.checkOrderByUserId(userId);
    }



    //根据订单号取消订单
    @Override
    public String cancelByOrderSn(Long orderId) {
        int result = orderMapper.deleteByOrderId(orderId);
        orderItemMapper.deleteByOrderId(orderId);
        if(result>0){
            return "success";
        }else{
            return "fail";
        }
    }
    //根据订单号确认收货
    @Override
    public String confirmByOrderId(Long orderId) {
        // 1. 根据订单号查询订单
        Orders orders = orderMapper.selectByOrderId(orderId);

        if (orders == null) {
            return "订单不存在";
        }

        // 2. 检查当前订单状态是否为2（未收货）
        if (orders.getOrderStatus() != (short) 2) {  // 显式转换为 short
            return "订单状态不是未收货状态，不能确认收货";
        }
        // 3. 修改订单状态为4（已收货）
        orders.setOrderStatus((short) 4);
        // 4. 更新订单到数据库
        int result = orderMapper.updateByOrderSn(orders);
        return result > 0 ? "success" : "fail";
    }

    /**
     * 根据订单号查询订单
     *
     * @param cartId
     * @return
     */
    @Override
    public List<Orders> checkOrderById(Long cartId) {

        Carts carts = cartMapper.getCartByCartId(cartId);
        if (carts == null){
            return null;
        }
        return orderMapper.getByUserId(carts.getUserId());
    }


    /*
     * 立即购买
     * */
    @Override
    public Integer buyOne(Long productId,Long userId) {
        //根据商品生成订单和订单号
        Orders orders = new Orders();
        orders.setUserId(userId);
        orders.setAddressId(9L);
        //订单Sn用雪花算法生成
        orders.setOrderSn(SnowFlake.getInstance().nextId());
        orders.setCreatedAt(LocalDateTime.now());
        orders.setOrderStatus((short) 2);
        orders.setFreightAmount(0.0);
        Double totalAmount = 0.0;
        Double payAmount = 0.0;
        int res = orderMapper.insert(orders); //插入订单

        if(res>0){
            ProductVO productVO = productFeignClient.getProductByProductId(productId).getBody();
            if(productVO==null) return null;
            Products products=productVO.getProduct();
            //获取商品
            if (products != null) {
                OrderItems orderItems = new OrderItems();
                //订单项注入值
                orderItems.setOrderId(orders.getOrderId());
                orderItems.setProductId(products.getProductId());
                orderItems.setProductName(products.getProductName());
                orderItems.setProductImage(products.getImage());
                orderItems.setProductPrice(products.getPrice());
                orderItems.setQuantity(1);
                //订单项总价
                orderItems.setTotalPrice(orderItems.getProductPrice() * orderItems.getQuantity());
                orderItemMapper.insert(orderItems); //插入订单项

                totalAmount +=orderItems.getTotalPrice() ;
                payAmount += orderItems.getTotalPrice() ;
            }
        }
        orderMapper.updateByOrderId(orders.getOrderId(),totalAmount,payAmount);
        return res;
    }
}


